package com.gpagers.kit.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.gpagers.kit.lucene.util.File2Document;

/**
 * 建立索引
 * 需要在sys.properties中配置
 * indexPath索引文件存放地址绝对路径
 * docPath被索引文件夹的绝对路径
 * tempDir lucene运行临时文件夹绝对路径
 * 
 * @author van
 * @time 2014年9月10日 下午4:34:01
 */
public class IndexFiles {

	private Analyzer analyzer;
	private Logger logger;
	
	public IndexFiles() {
		logger = LoggerFactory.getLogger(IndexFiles.class);
		analyzer = new IKAnalyzer();
	}
	
	/**
	 * 创建docPath下的文件索引到indexPath下<br>
	 * 创建索引是为了快速的检索对象
	 * @param indexPath 生成的索引存放地
	 * @param docPath 被索引文件的路径
	 * @throws Exception
	 */
	public void createIndex(String indexPath,String docPath) throws Exception {
		Directory directory = null;
		IndexWriter writer = null;
		try {
			directory = FSDirectory.open(new File(indexPath));
			IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_47, analyzer);
			//创建索引
			writerConfig.setOpenMode(OpenMode.CREATE);
			writer = new IndexWriter(directory, writerConfig);

			// 将需要索引的文件写到指定的位置，供搜索时候使用
			indexDocs(writer, new File(docPath));

			writer.commit();
			writer.close();
		} catch (Exception e) {
			logger.error("添加索引：失败");
			throw e;
		}
		logger.debug("添加索引：结束");
	}

	/**
	 * 
	 * @param writer
	 *            写索引的对象
	 * @param file
	 *            需要被索引的文件
	 * @throws Exception
	 */
	private void indexDocs(IndexWriter writer, File file) throws Exception {
		if (file.canRead()) {
			if (file.isDirectory()) {
				String[] files = file.list();
				if (files != null) {
					for (int i = 0; i < files.length; i++) {
						indexDocs(writer, new File(file, files[i]));
					}
				}
			} else {
				try {
					logger.debug("添加索引：" + file);
					File2Document f2d = new File2Document();
					for (Document doc : f2d.file2Document(file)) {
						writer.addDocument(doc);
					}
				} catch (CorruptIndexException e) {
					logger.error("添加索引错误"+file);
					throw e;
				} catch (IOException e) {
					logger.error("添加索引错误"+file);
					throw e;
				}
			}
		}
	}
}
